package org.example.com.controller;

import org.example.com.pojo.PostComment;
import org.example.com.pojo.Result;
import org.example.com.pojo.vo.PostCommentVO;
import org.example.com.service.PostCommentService;
import org.example.com.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 帖子评论Controller
 */
@RestController
@RequestMapping("/api/discover/posts")
public class PostCommentController {
    
    @Autowired
    private PostCommentService postCommentService;
    
    /**
     * 添加评论
     */
    @PostMapping("/{postId}/comments")
    public Result addComment(@PathVariable Integer postId, @RequestBody Map<String, Object> request) {
        try {
            // 获取当前用户信息
            Map<String, Object> claims = ThreadLocalUtil.get();
            Integer userId = (Integer) claims.get("id");
            String userName = (String) claims.get("name");
            String userAvatar = (String) claims.get("avatar");
            
            // 构建评论对象
            PostComment comment = new PostComment();
            comment.setPostId(postId);
            comment.setUserId(userId);
            comment.setUserName(userName);
            comment.setUserAvatar(userAvatar);
            comment.setContent((String) request.get("content"));
            
            // 处理回复评论
            Object parentIdObj = request.get("parentId");
            if (parentIdObj != null) {
                comment.setParentId((Integer) parentIdObj);
            }
            
            // 添加评论
            PostComment createdComment = postCommentService.addComment(comment);
            if (createdComment != null) {
                Map<String, Object> response = new HashMap<>();
                response.put("commentId", createdComment.getId());
                response.put("message", "评论添加成功");
                
                return Result.success(response);
            } else {
                return Result.error("评论添加失败");
            }
        } catch (Exception e) {
            return Result.error("评论失败：" + e.getMessage());
        }
    }
    
    /**
     * 根据帖子ID查询评论列表
     */
    @GetMapping("/{postId}/comments")
    public Result getCommentsByPostId(@PathVariable Integer postId,
                                    @RequestParam(defaultValue = "1") Integer page,
                                    @RequestParam(defaultValue = "10") Integer limit) {
        try {
            List<PostCommentVO> comments = postCommentService.getCommentsByPostId(postId, page, limit);
            
            Map<String, Object> response = new HashMap<>();
            response.put("comments", comments);
            response.put("page", page);
            response.put("limit", limit);
            response.put("total", comments.size());
            
            return Result.success(response);
        } catch (Exception e) {
            return Result.error("获取评论列表失败：" + e.getMessage());
        }
    }
    
    /**
     * 根据ID查询评论
     */
    @GetMapping("/comments/{id}")
    public Result getCommentById(@PathVariable Integer id) {
        try {
            PostComment comment = postCommentService.getCommentById(id);
            if (comment == null) {
                return Result.error("评论不存在");
            }
            
            return Result.success(comment);
        } catch (Exception e) {
            return Result.error("获取评论详情失败：" + e.getMessage());
        }
    }
    
    /**
     * 更新评论
     */
    @PutMapping("/comments/{id}")
    public Result updateComment(@PathVariable Integer id, @RequestBody Map<String, Object> request) {
        try {
            // 获取当前用户信息
            Map<String, Object> claims = ThreadLocalUtil.get();
            Integer userId = (Integer) claims.get("id");
            
            // 构建评论对象
            PostComment comment = new PostComment();
            comment.setId(id);
            comment.setUserId(userId);
            comment.setContent((String) request.get("content"));
            
            // 更新评论
            boolean success = postCommentService.updateComment(comment);
            if (success) {
                return Result.success("评论更新成功");
            } else {
                return Result.error("评论更新失败");
            }
        } catch (Exception e) {
            return Result.error("更新失败：" + e.getMessage());
        }
    }
    
    /**
     * 删除评论
     */
    @DeleteMapping("/comments/{id}")
    public Result deleteComment(@PathVariable Integer id) {
        try {
            // 获取当前用户信息
            Map<String, Object> claims = ThreadLocalUtil.get();
            @SuppressWarnings("unused")
            Integer userId = (Integer) claims.get("id");
            
            // 这里可以添加权限检查，确保只能删除自己的评论
            // 暂时省略，实际项目中应该添加
            
            boolean success = postCommentService.deleteComment(id);
            if (success) {
                return Result.success("评论删除成功");
            } else {
                return Result.error("评论删除失败");
            }
        } catch (Exception e) {
            return Result.error("删除失败：" + e.getMessage());
        }
    }
}
